import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Popconfirm, Card, Table, Button, Divider, Tag, message } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DescriptionList from '@/components/DescriptionList';
import ClientForm from './ClientForm';
import { humanizeTime, getOAuthTypeNames } from './ClientUtil';
import styles from '../Common/TableList.less';

const { Description } = DescriptionList;

@connect(({ client, loading }) => ({
  client,
  loading: loading.effects['client/fetch'],
  submitting: loading.effects['client/update'],
}))
class ClientList extends PureComponent {
  columns = [
    {
      title: '序号',
      dataIndex: 'index',
      render: (text, record, index) => index + 1,
    },
    {
      title: '应用ID',
      dataIndex: 'clientId',
    },
    {
      title: '应用名称',
      dataIndex: 'clientName',
    },
    {
      title: (
        <span>
          Token
          <br />
          有效期
        </span>
      ),
      dataIndex: 'accessTokenValidity',
      render: value => humanizeTime(value),
    },
    {
      title: (
        <span>
          RefreshToken
          <br />
          有效期
        </span>
      ),
      dataIndex: 'refreshTokenValidity',
      render: value => humanizeTime(value),
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (text, record) => (
        <span>
          <a
            onClick={() => {
              this.handleOpenForm(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <Popconfirm
            title="确认删除？"
            onConfirm={() => {
              this.handleRemove(record);
            }}
            okText="确认"
            cancelText="取消"
          >
            <a href="#">删除</a>
          </Popconfirm>
        </span>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'client/fetch' });
  }

  handleTableChange = pagination => {
    const { current, pageSize } = pagination;
    const { dispatch } = this.props;
    dispatch({ type: 'client/fetch', payload: { page: current - 1, size: pageSize } });
  };

  handleTableExpand = record => {
    const toTags = items => items.map((value, index) => <Tag key={index}>{value}</Tag>);
    return (
      <div>
        <DescriptionList size="small">
          <Description term="授权模式">
            {toTags(getOAuthTypeNames(record.authorizedGrantTypes))}
          </Description>
          <Description term="平台编码">{record.platformCode}</Description>
          <Description term="资源IDS">{record.resourceIds}</Description>
        </DescriptionList>
        <DescriptionList style={{ marginTop: 15 }} size="small">
          <Description term="短信验证码长度">{record.smsCodeLength}</Description>
          <Description term="短信验证码有效期">
            {record.smsCodeLength ? `${record.smsCodeLength}分钟` : ''}
          </Description>
          <Description term="短信验证码签名">{record.smsCodeSign}</Description>
        </DescriptionList>
      </div>
    );
  };

  handleOpenForm = formData => {
    const { dispatch } = this.props;
    dispatch({ type: 'client/openForm', payload: formData });
  };

  handleCloseForm = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'client/closeForm' });
  };

  handleAdd = values => {
    const { dispatch } = this.props;
    dispatch({ type: 'client/update', payload: values }).then(() => {
      message.success('操作成功');
    });
  };

  handleRemove = record => {
    const { dispatch } = this.props;
    dispatch({ type: 'client/remove', payload: record.clientId }).then(() => {
      message.success('删除成功');
    });
  };

  render() {
    const {
      client: { list, form },
      loading,
      submitting,
    } = this.props;
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...list.pagination,
    };
    return (
      <PageHeaderWrapper title="应用列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm} />
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={this.handleOpenForm}>
                新建
              </Button>
            </div>
            <Table
              rowKey="clientId"
              size="middle"
              columns={this.columns}
              loading={loading}
              dataSource={list.data}
              pagination={paginationProps}
              onChange={this.handleTableChange}
              expandedRowRender={this.handleTableExpand}
            />
          </div>
        </Card>
        <ClientForm
          data={form.data}
          visible={form.visible}
          submitting={submitting}
          onClose={this.handleCloseForm}
          onSave={this.handleAdd}
        />
      </PageHeaderWrapper>
    );
  }
}

export default ClientList;
